import router  from '@/router';
import axios from "axios";
import useUserStore from "@/stores/modules/user";
import { toast } from "@/utils";
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 30000,
  withCredentials: true
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    const UserStore = useUserStore();
    if (UserStore.token) {
      config.headers["token"] = UserStore.token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    const code = res.data.code;
    if(code && code === 403){
      const UserStore = useUserStore();
      UserStore.resetUserInfo();
      router.replace({ path: "/login" });
      toast(res.data.error, "error");
      return Promise.reject(res.data);
    }
    if (code && code !== 200) {
      toast(res.data.error, "error");
      return Promise.reject(res.data);
    }
    return res.request.responseType == "blob" ? res.data : res.data.data;
  },
  (error) => {
    const code = error.response.status;
    handleErrorStatus(code);
    return Promise.reject(error);
  }
);

const handleErrorStatus = (status: number) => {
  switch (status) {
    case 400:
      toast("请求参数错误！请您稍后重试", "error");
      break;
    case 401:
      toast("登录失效！请您重新登录", "error");
      break;
    case 403:
      toast("当前账号无权限访问！", "error");
      break;
    case 404:
      toast("你所访问的资源不存在！", "error");
      break;
    case 405:
      toast("请求方式错误！请您稍后重试", "error");
      break;
    case 408:
      toast("请求超时！请您稍后重试", "error");
      break;
    case 500:
      toast("服务异常！请您稍后重试", "error");
      break;
    case 502:
      toast("网关错误！请您稍后重试", "error");
      break;
    case 503:
      toast("服务不可用！请您稍后重试", "error");
      break;
    case 504:
      toast("网关超时！请您稍后重试", "error");
      break;
    default:
      toast("请求失败！请您稍后重试", "error");
  }
};
export default service;
